import React from "react";

import PageContent from '../../PageContent'

import { ajax ,showResultMessage,isNull} from '../../common';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import { Link } from 'react-router-dom';

import {Spin} from 'antd';

import UIFormView from '../../uicomponents/UIFormView';

import UICardTabs from '../../uicomponents/UICardTabs';

import UIView from '../../uicomponents/UIView';

import brace from 'brace';

import AceEditor from 'react-ace';

import 'brace/mode/html';

import 'brace/theme/github';

import { Base64 } from 'js-base64';

/** 
 *产品页面模板管理
*/
export default class ProductUIPageTemplateManageApp extends React.Component {

    state = {
		pageSearchValues : {},
	}

	onPageSearchValueChange = (values) => {
		this.setState({pageSearchValues : values});
	}


	render() {

        /**路由设置 */
		const pageContentMap = {
			'/': {
				text: '',
				icon: '',
				getComponent: (owner, props) => {
					return (<ProductUIPageTemplateListPanel {...props} 
						pageSearchValues={this.state.pageSearchValues} 
						onPageSearchValueChange={this.onPageSearchValueChange}
						key="uiPageTemplateList" 
						
						/>
						);
				}
			},
			'/editUIPageTemplate': {
				text: '编辑页面模板',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUIPageTemplatePanel {...props} key="editPageTemplate" />);
				}
            },
        }

		return (
			<PageContent {...this.props} pageInstance={this} contentMap={pageContentMap} >
				
			</PageContent>
		);
	}
}

class ProductUIPageTemplateListPanel extends React.Component {

    constructor(props) {
		super(props);
		this.state = {
            formTitle: '',
		}
    }

	actionHandler = (actionEvent) => {

		const { selectPageIds, pageListRef, pageFormRef } = this;

		return {
			refresh : () => {
				pageListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增页面模板'});
				setTimeout(() => {
					pageFormRef.openModal();
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑页面模板' });
				setTimeout(() => {
					pageFormRef.openModal(() => {
						pageFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectPageIds;
				}

				ajax('PRODUCT/UI/ProductUIPageTemplate/batchDelete', { ids: selectedIds }, (data) => {
					pageListRef.loadData();
				});
			},
			doSave : () => {
				pageFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/ProductUIPageTemplate/save', formData, (data) => {
						pageFormRef.closeModal();
						pageListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const pageProps = {
            ref: (inst) => { this.pageListRef = inst },
			history : this.props.history,
			title : "页面模板",
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIPageTemplateListActionGroup',
			rowActionGroupId: 'productUIPageTemplateRowActionGroup',
			tableConfigId: 'productUIPageTemplateListTable',
			dataUrl: 'PRODUCT/UI/ProductUIPageTemplate/query',
			selectMode: 'multi',
            searchFormId: 'productUIPageTemplateSearchForm',
            initSearchValues : this.props.pageSearchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectPageIds = selectRowKeys;
				}
            ,
            onSearchData : (changedValues) => {
				
				if(this.props.onPageSearchValueChange){
					this.props.onPageSearchValueChange(changedValues)
				}
			}
		};

		const pageFormProps = {
			ref: (inst) => { this.pageFormRef = inst },
			formConfigId: 'productUIPageTemplateForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...pageProps}>
				<UIFormView {...pageFormProps} />
			</UIDataTableView>
		);
	}
}

class EditProductUIPageTemplatePanel extends React.Component {

    constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
		}
	}
	
	componentDidMount(){
		this.pageTemplate = this.props.location.state;
		this.setState({pageTitle : '编辑[' + this.pageTemplate.templateName +   ']页面模板'});
	}

    actionHandler = (actionEvent) => {
		
		return {
			
		};
    }
    
    onTabChange = (tabName) => {
        switch (tabName) {
            case 'templateInfo':
                this.pageTemplateContentRef.loadPageTemplateContent(this.pageTemplate);
                break;
            case 'templateParamInfo':
                this.pageTemplateParamListRef.loadPageTemplateParams(this.pageTemplate);
                break;
		}
		
    }


	render () {

        const tabPanelContentMap = {
			
            '/ProductUIPageTemplateEditorPanel': {
                getComponent: (owner, props) => {
                    return <ProductUIPageTemplateEditorPanel pageTemplate={this.pageTemplate} {...props} ref={(inst) => this.pageTemplateContentRef = inst}/>;
                }
            },
            '/ProductUIPageTemplateParamListPanel': {
                getComponent: (owner, props) => {
                    return <ProductUIPageTemplateParamListPanel pageTemplate={this.pageTemplate} {...props}  ref={(inst) => this.pageTemplateParamListRef = inst}/>;
                }
            },
        };


		return (
            <UICardTabs 
                extra={<Link to="/">返回</Link>} 
                title={this.state.pageTitle}
                tabConfigId="uiPageTemplateTab"
                onTabChange={this.onTabChange}
                tabContentMap={tabPanelContentMap}
            >
				
			</UICardTabs>
		);
	}
}

class ProductUIPageTemplateEditorPanel extends React.Component {

    state = {
        pageTemplateContent : "",
        loading : false,
    }

    componentDidMount(){
        const {pageTemplate} = this.props;
        this.loadPageTemplateContent(pageTemplate);
    }

    loadPageTemplateContent = (pageTemplate) => {
        this.setState({loading : true});
        ajax('PRODUCT/UI/ProductUIPageTemplate/getById',{id : pageTemplate.id },(data) => {
            this.editContent = isNull(data.templateContent) ? '' : Base64.decode(data.templateContent);
            this.setState({pageTemplateContent :this.editContent ,loading : false});
        });
    }

    onEditorChange = (newValue) => {
		this.editContent = newValue;
	}

    actionHandler = (actionEvent) => {

        return {
            doSave : () => {
                const {pageTemplate} = this.props;

                pageTemplate.templateContent = Base64.encode(this.editContent);

				this.setState({loading : true});
				ajax('PRODUCT/UI/ProductUIPageTemplate/save',pageTemplate,(data) => {
					
					this.setState({loading : false,pageTemplateContent : this.editContent});
					showResultMessage({
						success : true,
                        message : 'message.saveSuccess',
					});
				});
            }
        };
    }

    render() {
        return (
            <UIView bordered={false} actionGroupId="saveActionGroup" actionHandler={this.actionHandler} ref={(inst) => this.pageCodeTemplateView = inst}>
                <Spin tip="保存中..." spinning={this.state.loading}>
                    <AceEditor mode="html" theme="github" width="100%" onChange={this.onEditorChange} readOnly={false} value={this.state.pageTemplateContent} ref={ (inst) => this.pageCodeTemplateEditor = inst } />
                </Spin>
            </UIView>
        );
    }
}

class ProductUIPageTemplateParamListPanel extends React.Component {

    componentDidMount(){
        const {pageTemplate} = this.props;
        this.loadPageTemplateParams(pageTemplate);
    }

    loadPageTemplateParams = (pageTemplate) => {
        this.pageParamListRef.loadData({pageTemplateId : pageTemplate.id});
    }

    actionHandler = (actionEvent) => {
        const {pageParamFormRef} = this;
        const {pageTemplate} = this.props;
        return {
            refresh : () => {
                
                this.loadPageTemplateParams(pageTemplate);
            },
            doEdit : () => {
                pageParamFormRef.openModal(() => {
                    pageParamFormRef.setFormData(actionEvent.params);
                });
            },
            doSave : () => {
                pageParamFormRef.getFormData( (formData) => {
                    ajax('PRODUCT/UI/ProductUIPageTemplateParam/save',formData,(data) => {
                        pageParamFormRef.closeModal();
                        this.loadPageTemplateParams(pageTemplate);
                    })
                } );
            }
        }
    }

    render() {
        const tableProps = {
			bordered : false,
			ref: (inst) => { this.pageParamListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'productUIPageTemplateParamListActionGroup',
			rowActionGroupId: 'productUIPageTemplateParamRowActionGroup',
			tableConfigId: 'productUIPageTemplateParamListTable',
			dataUrl: 'PRODUCT/UI/ProductUIPageTemplateParam/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		const formProps = {
			ref: (inst) => { this.pageParamFormRef = inst },
			formConfigId: 'productUIPageTemplateParamForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: '编辑参数',
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...formProps} />
			</UIDataTableView>
		);
    }
}